<template>
	<view class="address-page-container">
		<u-navbar title="地址管理" @leftClick="navigateBack" safeAreaInsetTop fixed placeholder></u-navbar>
		
		<view v-if="!addresses || addresses.length === 0" class="empty-state">
			<image src="/static/address/empty-address.png" class="empty-icon" />
			<text class="empty-text">您还没有添加收货地址</text>
		</view>

		<view v-else class="address-list">
			<view v-for="address in addresses" :key="address.id" class="address-card" @click="selectAddress(address)">
				<view class="card-content">
					<view class="user-info">
						<text class="user-name">{{ address.consignee }}</text>
						<text class="user-phone">{{ address.phone }}</text>
					</view>
					<view class="address-details">
						<text v-if="address.isDefault" class="default-tag">默认</text>
						<text class="address-text">{{ address.province }}{{ address.city }}{{ address.district }}{{ address.detailAddress }}</text>
					</view>
				</view>
				<view class="card-actions">
					<view class="set-default" @click.stop="setDefault(address)">
						<u-checkbox :checked="address.isDefault" shape="circle" activeColor="#fa3534"></u-checkbox>
						<text class="default-text">设为默认</text>
					</view>
					<view class="action-buttons">
						<text class="action-btn" @click.stop="editAddress(address)">编辑</text>
						<text class="action-btn-divider">|</text>
						<text class="action-btn" @click.stop="deleteAddress(address)">删除</text>
					</view>
				</view>
			</view>
		</view>

		<view class="add-address-button-wrapper">
			<u-button type="primary" shape="circle" @click="addAddress" icon="plus">新增收货地址</u-button>
		</view>
	</view>
</template>

<script>
export default {
    data() {
        return {
            addresses: [],
			isSelectionMode: false
        };
    },
	onLoad(options) {
		if (options.from) {
			this.isSelectionMode = true;
		}
	},
    onShow() {
        this.loadAddresses();
    },
    methods: {
		selectAddress(address) {
			if (this.isSelectionMode) {
				console.log('选择地址:', JSON.stringify(address));
				// 检查地址对象是否完整
				if (!address) {
					console.error('地址对象为空');
					uni.showToast({
						title: '地址信息不完整',
						icon: 'none'
					});
					return;
				}
				
				// 检查地址ID
				if (!address.id) {
					console.error('选择的地址没有ID');
					
					// 尝试查找其他可能的ID字段
					const possibleIdFields = ['_id', 'ID', 'addressId', 'address_id'];
					let foundId = null;
					
					possibleIdFields.forEach(field => {
						if (address[field]) {
							console.log(`找到可能的ID字段 ${field}:`, address[field]);
							foundId = address[field];
						}
					});
					
					if (foundId) {
						console.log('使用替代ID字段:', foundId);
						address.id = foundId;
					} else {
						uni.showToast({
							title: '地址信息不完整',
							icon: 'none'
						});
						return;
					}
				}
				
				// 确保ID是整数类型
				if (typeof address.id === 'string') {
					address.id = parseInt(address.id);
					console.log('转换后的地址ID:', address.id);
				}
				
				uni.setStorageSync('selectedAddress', address);
				console.log('已将地址保存到缓存:', JSON.stringify(address));
				uni.navigateBack();
			}
		},
        loadAddresses() {
			console.log('加载地址列表');
            this.$api.addressApi.list().then(res => {
				console.log('地址API返回:', JSON.stringify(res));
                if (res.code === 200 && res.data) {
                    // 检查每个地址对象的结构
                    res.data.forEach((addr, index) => {
                        console.log(`地址${index}:`, addr);
                        console.log(`地址${index} ID:`, addr.id);
                        console.log(`地址${index} ID类型:`, typeof addr.id);
                        
                        // 检查是否有其他可能的ID字段
                        const possibleIdFields = ['id', '_id', 'ID', 'addressId', 'address_id'];
                        possibleIdFields.forEach(field => {
                            if (addr[field]) {
                                console.log(`地址${index} 可能的ID字段 ${field}:`, addr[field]);
                            }
                        });
                    });
                    
                    this.addresses = res.data.map(addr => {
                        // 尝试找到ID字段
                        let id = addr.id;
                        if (!id && addr._id) id = addr._id;
                        if (!id && addr.ID) id = addr.ID;
                        if (!id && addr.addressId) id = addr.addressId;
                        if (!id && addr.address_id) id = addr.address_id;
                        
                        return {
                            ...addr,
                            id: id, // 确保有ID字段
                            isDefault: !!addr.isDefault || !!addr.is_default
                        };
                    });
					console.log('处理后的地址列表:', JSON.stringify(this.addresses));
                }
            }).catch(err => {
				console.error('地址加载失败:', err);
                uni.showToast({ title: '地址加载失败', icon: 'none' });
            });
        },
        addAddress() {
            uni.navigateTo({ url: '/pages/address/edit' });
        },
        editAddress(address) {
            // 将地址信息存储到本地，方便编辑页面读取
            uni.setStorageSync('editingAddress', address);
            uni.navigateTo({
                url: `/pages/address/edit?uuid=${address.uuid}`
            });
        },
        deleteAddress(address) {
            uni.showModal({
                title: '确认删除',
                content: '确定要删除这个地址吗？',
                success: (res) => {
                    if (res.confirm) {
                        this.$api.addressApi.delete(address.uuid).then(() => {
                            uni.showToast({ title: '删除成功' });
                            this.loadAddresses(); // 重新加载列表
                        }).catch(err => {
                            uni.showToast({ title: err.msg || '删除失败', icon: 'none' });
                        });
                    }
                }
            });
        },
        setDefault(address) {
            this.$api.addressApi.setDefault(address.uuid).then(() => {
                uni.showToast({ title: '设置成功' });
                this.loadAddresses(); // 重新加载列表
            }).catch(err => {
                uni.showToast({ title: err.msg || '设置失败', icon: 'none' });
            });
        },
        navigateBack() {
            uni.navigateBack();
        }
    },
};
</script>

<style lang="scss" scoped>
.address-page-container {
	background-color: #f5f5f5;
	min-height: 100vh;
	padding-bottom: 160rpx;
}

.empty-state {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding-top: 200rpx;
	.empty-icon {
		width: 200rpx;
		height: 200rpx;
		margin-bottom: 20rpx;
	}
	.empty-text {
		color: #999;
	}
}

.address-list {
    padding: 20rpx;
}

.address-card {
    background: #fff;
    padding: 30rpx;
    margin-bottom: 20rpx;
    border-radius: 16rpx;
    box-shadow: 0 4rpx 20rpx rgba(0,0,0,0.05);

    .card-content {
        .user-info {
            display: flex;
            align-items: center;
            margin-bottom: 20rpx;

            .user-name {
                font-size: 30rpx;
                font-weight: bold;
                margin-right: 20rpx;
            }

            .user-phone {
                font-size: 28rpx;
                color: #666;
            }
        }

        .address-details {
            display: flex;
            align-items: baseline;
            
            .default-tag {
                background-color: #fa3534;
                color: #fff;
                font-size: 20rpx;
                padding: 4rpx 12rpx;
                border-radius: 6rpx;
                margin-right: 10rpx;
                flex-shrink: 0;
            }

            .address-text {
                font-size: 28rpx;
                color: #333;
                line-height: 1.5;
            }
        }
    }

    .card-actions {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-top: 30rpx;
        padding-top: 20rpx;
        border-top: 1rpx solid #f5f5f5;

        .set-default {
            display: flex;
            align-items: center;
            .default-text {
                margin-left: 10rpx;
                font-size: 26rpx;
                color: #666;
            }
        }

        .action-buttons {
            display: flex;
            align-items: center;
            font-size: 26rpx;
            color: #999;

            .action-btn-divider {
                margin: 0 20rpx;
            }
        }
    }
}

.add-address-button-wrapper {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 20rpx 40rpx;
	padding-bottom: calc(20rpx + constant(safe-area-inset-bottom));
	padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
    background-color: #f5f5f5;
}
</style> 